# dead_letter_consumer.py
import pika
import json

def process_dead_letter(ch, method, properties, body):
    order_data = json.loads(body)
    order_id = order_data['order_id']

    # 模拟处理死信队列中的订单
    print(f"模拟处理死信队列中的订单:{order_id}")

    # 此处可以加入处理逻辑，比如回滚库存等操作

    ch.basic_ack(delivery_tag=method.delivery_tag)

if __name__ == '__main__':
    connection_params = pika.ConnectionParameters(
        host='localhost',
        virtual_host='order_vhost',
        credentials=pika.PlainCredentials('admin', '123')
    )
    connection = pika.BlockingConnection(connection_params)
    channel = connection.channel()

    # 定义死信队列和交换机
    channel.exchange_declare(exchange='dead_letter_exchange', exchange_type='fanout')
    channel.queue_declare(queue='dead_letter_queue', durable=True)
    channel.queue_bind(exchange='dead_letter_exchange', queue='dead_letter_queue')

    # 定义死信队列消费者
    channel.basic_consume(queue='dead_letter_queue', on_message_callback=process_dead_letter)

    print("Waiting for orders in dead_letter_queue. To exit press CTRL+C")
    try:
        channel.start_consuming()
    except KeyboardInterrupt:
        channel.stop_consuming()

    connection.close()

